package com.star.batchhandler.demo;

import java.sql.Connection;
import java.sql.Statement;
import java.sql.Types;

import javax.sql.DataSource;

public class BatchJob extends AbstractJob {
	private ISQLCommandScheduler sqlScheduler;

	public BatchJob(ISQLCommandScheduler sqlScheduler, DataSource ds) {
		super(ds, null);
		sqlScheduler.selfAddJob();
		this.sqlScheduler = sqlScheduler;
	}

	@Override
	public void run() {
		try {
			Command cmd = new Command(getUpdateSQL());
//			System.out.println(Thread.currentThread().getName()+" income!");
			sqlScheduler.addCommand(cmd);
			checkGT_1(sqlScheduler.getBatchResult(cmd));
			p("update:[id=247]");

			Connection conn = null;
			long id;
			try {
				conn = ds.getConnection();
				Statement stmt = conn.createStatement();
				checkRS1(stmt.executeQuery(selectSQL), "id");
				stmt.close();
				p(" query:[id=247]");

				stmt = conn.createStatement();
				id = getId(stmt.executeQuery(selectSEQ), "nextval");
				stmt.close();
				p(" getSQadmin:[id=" + id + "]");
			} finally {
				if (conn != null)
					conn.close();
			}
			Command cmd_insert = new Command(getInsertSQL(), new int[] { Types.NUMERIC },
					new Object[] { id });
			sqlScheduler.addCommand(cmd_insert);
			
			
			checkLT_2(sqlScheduler.getBatchResult(cmd_insert));
			p(" insert:[id=" + id + "]");

			synchronized (timeLock) {
				sqlScheduler.selfDelJob();
				if (sqlScheduler.getJobs().equals(new Integer(0))) {
					if(SQLBatchOperation.lastBatch)
						System.out.println("$$$$$$$$$$$$$$$$$$\n" +
							"total consume time:" + (System.nanoTime()-SQLBatchOperation.begin)/(1000.0*1000) + " ms\n" 
							);
					sqlScheduler.setFinished();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new IllegalStateException("job exception!",e);
		}
	}
	
	private void p(String msg){
		System.out.println(msg);
	}
}
